﻿using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Core;
using DongFangGuoKai.WMSPlatform.Domain.AGVModels;
using DongFangGuoKai.WMSPlatform.Domain.Enums;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using DongFangGuoKai.WMSPlatform.Domain.WCSModels;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;

namespace DongFangGuoKai.WMSPlatform.Service
{
    public partial class ExternaService
    {

        /// <summary>
        /// 空箱分配储位
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="model"></param>
        /// <returns></returns>  
        public bool ConveyorLineContainerFinsh(out string msg, ConveyorLineContainerModel model)
        {
            msg = string.Empty;
            bool flag = false;

            var cellDal = PalletRepo.ChangeRepository<Repository<t_Cell>>();
            var instructDal = PalletRepo.ChangeRepository<Repository<t_Instruct>>();
            lock (_lock)
            {

                var pallnet = PalletRepo.GetFirst(t => t.PalletBarcode == model.PalletBarcode);
                if (pallnet == null)
                {
                    msg = $"{model.PalletBarcode}托盘不存在";
                    return false;
                }
                if (pallnet.Status == 0)
                {
                    msg = $"{model.PalletBarcode}托盘已禁用";
                    return false;

                }
                if (!pallnet.LocationCode.IsNullOrEmpty())
                {
                    msg = $"{model.PalletBarcode}托盘已在储位：{pallnet.LocationName}";
                    return false;

                }

                string logicPartCode = pallnet.LogicalPartCode;
                string palletBarcode = pallnet.PalletBarcode;
                var allocateCell = cellDal.AsQueryable()
                    .IgnoreColumns("Islock")
                    .Where(t => t.LogicalPartCode == "DistributionArea" && t.IsLock == false && t.BusinessType == 0 && t.Status == 1 && t.FullStatus == 0 && t.ColumnNO <= 4)
                    .OrderBy(o => o.LineNO)
                    .OrderBy(o => o.LayerNO)
                    .OrderBy(o => o.ColumnNO)
                    .First();
                if (allocateCell == null)
                {
                    allocateCell = cellDal.AsQueryable()
                     .Where(t => t.LogicalPartCode == logicPartCode && t.IsLock == false && t.Status == 1 && t.BusinessType == 0 && t.FullStatus == 0)
                     .OrderBy(o => o.LineNO)
                     .OrderBy(o => o.LayerNO)
                     .OrderBy(o => o.ColumnNO)
                     .First();
                }
                if (allocateCell == null)
                {
                    msg = "无可用仓位";
                    return false;
                }

                var newPallet = PalletRepo.GetFirst(t => t.LocationCode == allocateCell.Code);
                if (newPallet != null)
                {
                    msg = $" {allocateCell.Name}：{newPallet.PalletName}已存在托盘";
                    return false;
                }
                PalletRepo.AsTenant().BeginTran();
                try
                {
                    pallnet.LocationCode = allocateCell.Code;
                    pallnet.LocationName = allocateCell.Name;
                    pallnet.ERPLocationName = allocateCell.ERPCode;
                    pallnet.WarehouseId = allocateCell.WhId;
                    pallnet.WarehouseCode = allocateCell.WhCode;
                    pallnet.WarehouseName = allocateCell.WhName;

                    flag = PalletRepo.Update(pallnet);
                    if (!flag)
                    {
                        PalletRepo.AsTenant().RollbackTran();
                        msg = "修改托盘失败";
                        return false;
                    }
                    allocateCell.Status = 2;//锁定 
                    allocateCell.FullStatus = 0; //空箱
                    allocateCell.BusinessType = EmBusinessType.Move;  //入库  
                    flag = cellDal.Update(allocateCell);

                    if (!flag)
                    {
                        PalletRepo.AsTenant().RollbackTran();
                        msg = "修改仓位失败";
                        return false;
                    }

                    Guid guid = Guid.NewGuid();
                    t_Instruct instruct = new t_Instruct()
                    {
                        BusinessGroupId = guid,
                        CreateUserId = 1,
                        CreateUserName = "admin",
                        Status = 2,
                        Action = EmDeviceAction.Transport,
                        WorkDeviceType = EmWorkDeviceType.AGV,
                        InstructType = EmInstructType.Move,
                        ExpectedToLocation = allocateCell.Code,//目标地址
                        FromLocation = "S00001S1502013",   //源地址
                        InstructIndex = 1,
                        PalletBarcode = palletBarcode,
                        ScanedBarcode = palletBarcode,
                        Priority = 9999,
                        FinishedQTY = 0,
                        LogicalCellAddr = allocateCell.ERPCode,
                        StartTime = DateTime.Now,
                    };
                    flag = instructDal.Insert(instruct);
                    if (!flag)
                    {
                        msg = "指令保存失败";
                        PalletRepo.AsTenant().RollbackTran();
                        return false;
                    }
                    string ctnrType = "";
                    if (pallnet.Type == 1)
                    {
                        ctnrType = "2";
                    }
                    else if (pallnet.Type == 2)
                    {
                        ctnrType = "1";
                    }
                    //添加任务单
                    AddTaskModel taskModel = new AddTaskModel();

                    //生成32位uuid
                    taskModel.reqCode = guid.ToString("N");
                    taskModel.clientCode = "PDA";
                    //大料箱任务类型
                    taskModel.TaskTyp = "A13";


                    taskModel.CtnrTyp = ctnrType;
                    //生成36位uuid
                    taskModel.taskCode = guid.ToString();

                    //任务起始点仓位编码
                    taskModel.PositionCodePath = new PositionCodePathDto[2] {
                    new PositionCodePathDto() {
                        PositionCode="S00001S1502013",// 起始地址 D00080A2502013
                        Type="05"
                    },
                    new PositionCodePathDto() {
                        PositionCode=allocateCell.ERPCode,//ERP目标地址
                        Type="05"
                    }
                };
                    var res = AGVApiService.CreateTask(taskModel);
                    if (res.code == "1")
                    {
                        //  tran.Rollback();
                        msg = "AGV调用失败：" + res.message;
                        return false;
                    }
                    msg = allocateCell.AreaName + ":" + allocateCell.Name;
                    PalletRepo.AsTenant().CommitTran();  
                    return true;

                }
                catch (Exception ex)
                {
                    PalletRepo.AsTenant().RollbackTran();
                    Logger.LogError(ex.Message);
                    msg = "异常：" + ex.Message;
                    return false;
                }
               
            }
        }


        /// <summary>
        /// WCS通知托盘到达指定窗口
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool ConveyorLineWindowFinsh(out string msg, ConveyorLineOverModel model)
        {
            msg = string.Empty;
            bool flag = false;

            string orderSn = model.OrderSn;
            //查看托盘对应委托单，对应几个托盘，对应的托盘是否出完。 该委托单只有剩余这1个托盘进行出库。
            if (string.IsNullOrEmpty(orderSn))
            {
                //查看对应委托单号
            }
            var quece = queceRepository.GetFirst(t => t.BillNO == orderSn && t.CallStatus == 0 || t.DisplayStatus == 0);
            if (quece == null)
            {
                msg = "客户未现场取样预约！";
                return false;

            }
            if (quece.CallStatus == 2)
            {
                msg = "该委托单已叫号！";
                return false;

            }
            if (quece.CallStatus != 0)
            {
                msg = "该委托单已叫号！";
                return false;

            }
            //可显示可叫号           
            quece.CallStatus = 1;
            quece.DisplayStatus = 1;
            queceRepository.Update(quece);

            return true;


        }
    }
}
